<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实体变更日志</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <style>
        .log-table th, .log-table td {
            vertical-align: middle;
        }
        .diff-highlight {
            background-color: #fff3cd;
            color: #856404;
        }
        .field-description {
            font-weight: bold;
            color: #007bff;
        }
        .nested-field {
            margin-left: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <h2>实体变更日志</h2>
        
        <!-- 筛选条件 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5>筛选条件</h5>
            </div>
            <div class="card-body">
                <form id="filterForm">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="entityClass">实体类名</label>
                                <input type="text" class="form-control" id="entityClass" placeholder="输入实体类名">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="operationType">操作类型</label>
                                <select class="form-control" id="operationType">
                                    <option value="">全部</option>
                                    <option value="INSERT">新增</option>
                                    <option value="UPDATE">修改</option>
                                    <option value="DELETE">删除</option>
                                    <option value="SELECT">查询</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="username">操作用户</label>
                                <input type="text" class="form-control" id="username" placeholder="输入用户名">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <div>
                                    <button type="button" class="btn btn-primary" onclick="searchLogs()">查询</button>
                                    <button type="button" class="btn btn-secondary" onclick="resetFilter()">重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 日志列表 -->
        <div class="card">
            <div class="card-header">
                <h5>变更记录列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered log-table">
                        <thead>
                            <tr>
                                <th>操作时间</th>
                                <th>操作用户</th>
                                <th>实体类名</th>
                                <th>操作类型</th>
                                <th>实体ID</th>
                                <th>操作描述</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="logTableBody">
                            <!-- 日志数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
                <nav>
                    <ul class="pagination justify-content-center" id="pagination">
                        <!-- 分页控件将通过JavaScript动态加载 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>
    
    <!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">变更详情</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="detailContent">
                        <!-- 详情内容将通过JavaScript动态加载 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 1;
        let currentLogs = [];
        
        // 页面加载完成后获取日志数据
        $(document).ready(function() {
            searchLogs();
        });
        
        // 查询日志
        function searchLogs() {
            const entityClass = $('#entityClass').val();
            const operationType = $('#operationType').val();
            const username = $('#username').val();
            
            const params = {
                page: currentPage,
                limit: 10,
                entityClass: entityClass,
                operationType: operationType,
                username: username
            };
            
            // 实际API调用
            $.get('/sys/entityChangeLog/list', params, function(response) {
                if (response.code === 0) {
                    renderLogs(response.page.list);
                    renderPagination(response.page);
                } else {
                    alert('获取日志数据失败: ' + response.msg);
                }
            }).fail(function() {
                alert('请求失败，请检查网络连接');
            });
        }
        
        // 重置筛选条件
        function resetFilter() {
            $('#entityClass').val('');
            $('#operationType').val('');
            $('#username').val('');
            currentPage = 1;
            searchLogs();
        }
        
        // 渲染日志列表
        function renderLogs(logs) {
            currentLogs = logs;
            const tbody = $('#logTableBody');
            tbody.empty();
            
            if (!logs || logs.length === 0) {
                tbody.append('<tr><td colspan="7" class="text-center">暂无数据</td></tr>');
                return;
            }
            
            logs.forEach(log => {
                const row = `
                    <tr>
                        <td>${log.createDate}</td>
                        <td>${log.username}</td>
                        <td>${log.entityClass ? log.entityClass.substring(log.entityClass.lastIndexOf('.') + 1) : ''}</td>
                        <td>
                            <span class="badge badge-${getOperationTypeClass(log.operationType)}">
                                ${getOperationTypeText(log.operationType)}
                            </span>
                        </td>
                        <td>${log.entityId || ''}</td>
                        <td>${log.operation}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="showDetail(${log.id})">详情</button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }
        
        // 获取操作类型样式类
        function getOperationTypeClass(operationType) {
            switch (operationType) {
                case 'INSERT': return 'success';
                case 'UPDATE': return 'warning';
                case 'DELETE': return 'danger';
                default: return 'secondary';
            }
        }
        
        // 获取操作类型文本
        function getOperationTypeText(operationType) {
            switch (operationType) {
                case 'INSERT': return '新增';
                case 'UPDATE': return '修改';
                case 'DELETE': return '删除';
                case 'SELECT': return '查询';
                default: return operationType;
            }
        }
        
        // 渲染分页控件
        function renderPagination(page) {
            const pagination = $('#pagination');
            pagination.empty();
            
            if (page.totalPage <= 1) {
                return;
            }
            
            // 上一页
            const prevDisabled = page.currPage === 1 ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${prevDisabled}">
                    <a class="page-link" href="#" onclick="changePage(${page.currPage - 1})">上一页</a>
                </li>
            `);
            
            // 页码
            for (let i = 1; i <= page.totalPage; i++) {
                const active = i === page.currPage ? 'active' : '';
                pagination.append(`
                    <li class="page-item ${active}">
                        <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                    </li>
                `);
            }
            
            // 下一页
            const nextDisabled = page.currPage === page.totalPage ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${nextDisabled}">
                    <a class="page-link" href="#" onclick="changePage(${page.currPage + 1})">下一页</a>
                </li>
            `);
        }
        
        // 切换页面
        function changePage(page) {
            currentPage = page;
            searchLogs();
        }
        
        // 显示详情
        function showDetail(logId) {
            // 实际API调用获取详情
            $.get('/sys/entityChangeLog/info?id=' + logId, function(response) {
                if (response.code === 0) {
                    renderDetailModal(response.data);
                } else {
                    alert('获取详情失败: ' + response.msg);
                }
            }).fail(function() {
                alert('请求失败，请检查网络连接');
            });
        }
        
        // 渲染详情模态框
        function renderDetailModal(log) {
            let detailHtml = `
                <div class="row">
                    <div class="col-md-6">
                        <h6>基本信息</h6>
                        <table class="table table-sm">
                            <tr>
                                <td>操作时间:</td>
                                <td>${log.createDate}</td>
                            </tr>
                            <tr>
                                <td>操作用户:</td>
                                <td>${log.username}</td>
                            </tr>
                            <tr>
                                <td>实体类名:</td>
                                <td>${log.entityClass || ''}</td>
                            </tr>
                            <tr>
                                <td>操作类型:</td>
                                <td>${getOperationTypeText(log.operationType)}</td>
                            </tr>
                            <tr>
                                <td>实体ID:</td>
                                <td>${log.entityId || ''}</td>
                            </tr>
                            <tr>
                                <td>操作描述:</td>
                                <td>${log.operation}</td>
                            </tr>
                        </table>
                    </div>
                </div>
            `;
            
            // 如果有详细的字段变更信息，则优先显示
            if (log.detailedFieldChanges && log.detailedFieldChanges.length > 0) {
                detailHtml += `
                    <div class="row mt-4">
                        <div class="col-12">
                            <h6>详细变更信息</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm">
                                    <thead>
                                        <tr>
                                            <th>字段路径</th>
                                            <th>字段描述</th>
                                            <th>变更前</th>
                                            <th>变更后</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${renderDetailedDiffTable(log.detailedFieldChanges)}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                `;
            } else if (log.operationType === 'UPDATE' && log.beforeData && log.afterData) {
                // 显示变更详情
                detailHtml += `
                    <div class="row mt-4">
                        <div class="col-12">
                            <h6>变更详情</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm">
                                    <thead>
                                        <tr>
                                            <th>字段</th>
                                            <th>变更前</th>
                                            <th>变更后</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${renderDiffTable(log.beforeData, log.afterData)}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                `;
            } else if (log.afterData) {
                // 显示新增或查询的数据
                detailHtml += `
                    <div class="row mt-4">
                        <div class="col-12">
                            <h6>数据详情</h6>
                            <pre>${formatJson(log.afterData)}</pre>
                        </div>
                    </div>
                `;
            }
            
            $('#detailContent').html(detailHtml);
            $('#detailModal').modal('show');
        }
        
        // 渲染详细差异表格（包含字段描述）
        function renderDetailedDiffTable(detailedChanges) {
            let html = '';
            
            if (!detailedChanges || detailedChanges.length === 0) {
                return '<tr><td colspan="4" class="text-center">无详细变更信息</td></tr>';
            }
            
            detailedChanges.forEach(change => {
                const fieldName = change.fieldName || '';
                const fieldDescription = change.fieldDescription || fieldName;
                const oldValue = change.oldValue !== undefined ? formatValue(change.oldValue) : '-';
                const newValue = change.newValue !== undefined ? formatValue(change.newValue) : '-';
                const isChanged = change.oldValue !== change.newValue;
                
                html += `
                    <tr ${isChanged ? 'class="diff-highlight"' : ''}>
                        <td>${fieldName}</td>
                        <td class="field-description">${fieldDescription}</td>
                        <td>${oldValue}</td>
                        <td>${newValue}</td>
                    </tr>
                `;
            });
            
            return html;
        }
        
        // 渲染差异表格
        function renderDiffTable(beforeData, afterData) {
            try {
                const beforeObj = JSON.parse(beforeData);
                const afterObj = JSON.parse(afterData);
                
                let html = '';
                const allKeys = new Set([...Object.keys(beforeObj), ...Object.keys(afterObj)]);
                
                allKeys.forEach(key => {
                    const beforeValue = beforeObj[key];
                    const afterValue = afterObj[key];
                    const isChanged = beforeValue !== afterValue;
                    
                    html += `
                        <tr ${isChanged ? 'class="diff-highlight"' : ''}>
                            <td>${key}</td>
                            <td>${beforeValue === undefined ? '-' : formatValue(beforeValue)}</td>
                            <td>${afterValue === undefined ? '-' : formatValue(afterValue)}</td>
                        </tr>
                    `;
                });
                
                return html;
            } catch (e) {
                return `<tr><td colspan="3">数据解析错误: ${e.message}</td></tr>`;
            }
        }
        
        // 格式化值显示
        function formatValue(value) {
            if (value === null) return '<span class="text-muted">null</span>';
            if (value === undefined) return '<span class="text-muted">undefined</span>';
            if (typeof value === 'object') {
                // 如果是简单对象，直接显示
                if (value instanceof Array && value.length === 0) {
                    return '<span class="text-muted">[]</span>';
                }
                if (Object.keys(value).length === 0 && value.constructor === Object) {
                    return '<span class="text-muted">{}</span>';
                }
                return '<pre>' + JSON.stringify(value, null, 2) + '</pre>';
            }
            return String(value);
        }
        
        // 格式化JSON
        function formatJson(jsonStr) {
            try {
                const obj = JSON.parse(jsonStr);
                return JSON.stringify(obj, null, 2);
            } catch (e) {
                return jsonStr;
            }
        }
    </script>
</body>
</html>